package com.nl.mobile.commuteaid.tools;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import org.xmlpull.v1.XmlPullParserException;

import android.os.AsyncTask;
import android.util.Log;
import android.widget.TextView;

import com.nl.mobile.commuteaid.data.TFLStationStatus;

public class TFLFeedDownloader extends AsyncTask<Object, Void, List<TFLStationStatus>> {

	private static final String DEBUG_TAG = "DEBUG ASYNC TASK";
	private TextView textView;

	@Override
	protected List<TFLStationStatus> doInBackground(Object... params) {
		this.textView = (TextView)params[0];
		try {
			return downloadUrl((String)params[1]);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	private List<TFLStationStatus> downloadUrl(String myurl) throws IOException {
	    InputStream is = null;
	        
	    try {
	        URL url = new URL(myurl);
	        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
	        conn.setReadTimeout(10000 /* milliseconds */);
	        conn.setConnectTimeout(15000 /* milliseconds */);
	        conn.setRequestMethod("GET");
	        conn.setDoInput(true);
	        // Starts the query
	        conn.connect();
	        int response = conn.getResponseCode();
	        Log.d(DEBUG_TAG, "The response is: " + response);
	        is = conn.getInputStream();

	        TFLFeedParser parser = new TFLFeedParser();
	        return parser.fetchStationStatues(is);

		    // Makes sure that the InputStream is closed after the app is
		    // finished using it.
	    } catch (XmlPullParserException e) {
			e.printStackTrace();
			return null;
		} finally {
	        if (is != null) {
	            is.close();   
	        } 
	    }
	}
	
    @Override
    protected void onPostExecute(List<TFLStationStatus> result) {
    	String text = "";
    	for(TFLStationStatus s:result) {
    		text += s.getLineName() + " - " + s.getStatus() + "\n";
    	}
        this.textView.setText(text.toString());
   }
}
